package com.mywang.weitravel.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.mywang.weitravel.R;
import com.mywang.weitravel.util.ScreenUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangmingyun on 2019/12/10.
 */
public class AddFindAdapter extends RecyclerView.Adapter<AddFindAdapter.AddFindHolder> {

    private List<String> pic_path = new ArrayList<>();

    private Context mContext;

    private OnAddListener mOnAddListener;

    private final int IMAGE_WIDTH = (ScreenUtil.getScreenWidth() - 5 * ScreenUtil.dp2px(16)) / 4;

    public AddFindAdapter(Context context, OnAddListener onAddListener) {
        this.mContext = context;
        this.mOnAddListener = onAddListener;
    }

    public void addData(String path) {
        pic_path.add(path);
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public AddFindHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_add_find, null);
        return new AddFindHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull AddFindHolder addFindHolder, int i) {
        String path = pic_path.get(i);
        addFindHolder.iv_pic.getLayoutParams().width = IMAGE_WIDTH;
        addFindHolder.iv_pic.getLayoutParams().height = IMAGE_WIDTH;
        if (path.equals("add")) {
            addFindHolder.iv_pic.setImageResource(R.mipmap.icon_add);
        } else {
            Glide.with(mContext).asBitmap().load(path).into(addFindHolder.iv_pic);
        }
        addFindHolder.iv_pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (path.equals("add")) {
                    mOnAddListener.addPic();
                } else {
                    mOnAddListener.preview(i);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return pic_path.size();
    }

    public void setList(List<String> selectList) {
        pic_path.clear();
        if (selectList != null && !selectList.isEmpty()) {
            pic_path.addAll(selectList);
        }
        if (pic_path.size() < 4) {
            addData("add");
        } else {
            notifyDataSetChanged();
        }
    }

    class AddFindHolder extends RecyclerView.ViewHolder {
        ImageView iv_pic;

        public AddFindHolder(@NonNull View itemView) {
            super(itemView);
            iv_pic = itemView.findViewById(R.id.iv_pic);
        }
    }

    public interface OnAddListener {
        void addPic();

        void preview(int position);
    }
}
